var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var cors = require('cors');
var app = express();
const userRouter = require('./routes/users')
const faceRouter = require('./routes/face')
const orderRouter = require('./routes/order')
app.use(cors());
app.use(userRouter)
app.use(faceRouter)
app.use(orderRouter)

// app.use(express.bodyParser({limit:"300kb"}))
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');



app.use(logger('dev'));
app.use(express.json({limit:"300kb"}));
app.use(express.urlencoded({ extended: false }));
// 韩博洋在此处做出修改
app.use(express.json({limit:'5mb'}));
app.use(express.urlencoded({ extended: false,limit:'5mb' }));
app.use(cookieParser());
app.use("/public",express.static(path.join(__dirname, 'public')));

//验证是否过期
const {yz_accessToken} = require("./token/index")

app.use((req,res,next)=>{
  if(['/login','/yzm_login',"/token","/sendCode","/resetpassword","/register",'/sfrz'].includes(req.path)){
    return next()
  }
  let token = req.headers.authorization
  let code = 209
  if(token){
    code = yz_accessToken(token)
    console.log( yz_accessToken(token),10)
    if(code==200){
      next()
    }else{
      res.status(500).send({msg:"token过期"})
    }
  }else{
    res.status(500).send({msg:"token过期"})
  }
})

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use((req,res)=>{
  res.setHeader('Content-Encoding', 'gzip');
  const gzip = zlib.gzipSync(text);
  res.end(gzip);
})
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
